package com.jiarong.service.impl;

import com.jiarong.domain.Role;
import com.jiarong.domain.User;
import com.jiarong.repository.RoleDao;
import com.jiarong.repository.UserDao;
import com.jiarong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 加绒
 * @date 2021/10/16 0:06
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<User> list() {
        List<User> userList = userDao.selectAll();
        // 封装userList中的每一个User的roles数据
        for (User user : userList) {
            // 获得user的id
            Long id = user.getId();
            // 将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roles = roleDao.selectRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }

    @Override
    public void save(User user, Long[] roleIds) {
        Long userId = userDao.insertUser(user);
        userDao.insertUserRoleRelation(userId, roleIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long userId) {
        userDao.deleteUserRoleRelationByUserId(userId);
        userDao.deleteUser(userId);
    }

    @Override
    public User login(String username, String password) {
        try {
            return userDao.login(username, password);
        } catch (EmptyResultDataAccessException e) {
            // 登录信息错误则返回null
            return null;
        }
    }
}
